import { Player, world } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { Game, GameComponent } from "@sapi-game/main";
import { DimensionIds, EffectIds } from "@sapi-game/utils/vanila-data";
import { KcpdBackState } from "./kcpdBack";
import { CubeRegion } from "@sapi-game/gameRegion/gameRegion";
import { KcpdFuncs } from "../func";

export class KcpdBackDoorComponent extends GameComponent<KcpdBackState> {
    speedRegion = new CubeRegion(
        DimensionIds.Overworld,
        { x: -160, y: -60, z: -384 },
        { x: -175, y: -56, z: -386 }
    );

    joinRegion = new CubeRegion(
        DimensionIds.Overworld,
        {
            x: -174,
            y: -59,
            z: -384,
        },
        { x: -175, y: -57, z: -386 }
    );

    override onAttach(): void {
        this.subscribe(Game.events.buttonPush, () => this.openDoor(), {
            loc: [-158, -58, -385],
            dimensionId: DimensionIds.Overworld,
        });
        this.subscribe(Game.events.interval, () => {
            this.speedRegion.forEachPlayer((p) =>
                p.addEffect(EffectIds.Speed, 5, {
                    amplifier: 10,
                    showParticles: false,
                })
            );
            this.joinRegion.forEachPlayer((p) => {
                this.joinGame(p);
            });
        });
        KcpdFuncs.reloadDoor();
    }

    openDoor() {
        Dimensions.Overworld.runCommand(
            "fill -159 -57 -384 -158 -59 -386 air destroy"
        );
        Dimensions.Overworld.runCommand(
            "kill @e[type=item,r=5,x=-159,y=-58,z=-385]"
        );
    }

    //加入游戏
    joinGame(p: Player) {
        const gamePlayer = this.state.playerManager.get(p);
        this.state.players.add(gamePlayer);
        gamePlayer.player?.teleport({
            x: -145.83,
            y: -53.0,
            z: -367.98,
        }); //传送
        gamePlayer.runCommand("me 加入了烤肠派对！");
    }
}
